package logs

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
	"os"
	"time"
)

type LogConfig struct {
	Name       string
	MaxSize    int
	MaxBackups int
	MaxAge     int
	Compress   bool
}

func InitLogs(c *LogConfig) {
	// 设置 lumberjack.Logger 作为 zap 日志的输出
	writeSync := zapcore.AddSync(&lumberjack.Logger{
		Filename:   c.Name,       // 日志文件路径
		MaxSize:    c.MaxSize,    // 每个日志文件保存的最大尺寸 单位：M
		MaxBackups: c.MaxBackups, // 日志文件最多保存多少个备份
		MaxAge:     c.MaxAge,     // 文件最多保存多少天
		Compress:   c.Compress,   // 是否压缩
	})

	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.TimeKey = "time"
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	jsonEncoder := zapcore.NewJSONEncoder(encoderConfig)

	writeCore := zapcore.NewCore(jsonEncoder, writeSync, zapcore.DebugLevel)

	consoleEncoder := zapcore.NewConsoleEncoder(zap.NewDevelopmentEncoderConfig())
	consoleCore := zapcore.NewCore(consoleEncoder, zapcore.Lock(os.Stdout), zapcore.DebugLevel)
	cores := zapcore.NewTee(writeCore, consoleCore)
	logger := zap.New(cores, zap.AddCaller())
	zap.ReplaceGlobals(logger)
}

func ZapLogger() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		path := c.Request.URL.Path
		query := c.Request.URL.RawQuery
		c.Next()

		cost := time.Since(start)
		zap.L().Info(path,
			zap.Int("status", c.Writer.Status()),
			zap.String("method", c.Request.Method),
			zap.String("path", path),
			zap.String("query", query),
			zap.String("ip", c.ClientIP()),
			zap.String("user-agent", c.Request.UserAgent()),
			zap.String("errors", c.Errors.ByType(gin.ErrorTypePrivate).String()),
			zap.Duration("cost", cost),
		)
	}
}
